package threadPool;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutoeTest {
    public static void main(String[] args) {
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,4,60,
//                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
        // 拒绝策略，当给定等待队列的大小后，运行线程达到最大线程数和队列大小总和后，再来的线程
        // 需要采用拒绝策略，官方提供的决绝策略有如下几种
        /**
         * 1.AbortPolicy 抛出异常，不影响其他线程运行
         * 2.CallerRunsPolicy 调用当前任务（不使用线程池）。使用主线程（创建线程池的线程）执行
         * 3.DiscardOldestPolicy 丢弃老的任务(老的未执行的任务)
         * 4.DiscardPolicy 直接丢弃，什么也不做
         */
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,4,60,
//                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1),
//                new ThreadPoolExecutor.AbortPolicy());
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,4,60,
//                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1),
//                new ThreadPoolExecutor.CallerRunsPolicy());
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4,4,60,
//                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1),
//                new ThreadPoolExecutor.DiscardOldestPolicy());
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4,4,60,
//                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1),
//                new ThreadPoolExecutor.DiscardPolicy());
        // 自定义拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4,4,60,
                TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(1),
                new RejectedExecutionHandler(){
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println(r + " 被拒绝处理 = ");
                    }
                });
        for (int i = 0; i < 10; i++) {
            MytASK mytASK = new MytASK(i);
            threadPoolExecutor.execute(mytASK);
        }
        threadPoolExecutor.shutdown();
    }
}
class MytASK implements Runnable{
    int index = 0;

    public MytASK(int index) {
        this.index = index;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ">> run" + index);
    }
}